# Concave
# Copyright (C) 2012 Daniel Malmqvist
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import pygame
pygame.init()
import random
import pyhunter
import sys
import g
import ccredits
from pygame.locals import *
import helperfunctions
import os

class Snow():
    def __init__(self,x,y, speed):
        self.x = x
        self.y = y
        self.speed = self.speed = random.randint(1,5)
        self.color = (random.randint(0,255), random.randint(0,255), random.randint(0,255))
    def update(self):
        self.x -= self.speed
        if self.x < 0:
            self.x = 640 + self.speed
    def getPos(self):
        return (self.x, self.y)

def getCharsAvalible():
    files = os.listdir(os.getcwd())
    chars = []
    for f in files:
        if f.endswith(".sav"):
            charName = f.replace(".sav", "")
            
            charNameImage = helperfunctions.renderTextBlock(charName, g.fontBig, 1, (255,255,255))
            charNameImage = helperfunctions.addBorderCentered(charNameImage)
            
            chars.append((charName, charNameImage))
    return chars

def readPrevChar():
    try:
        configFile = open("concave.cfg", "r")
        prevChar = configFile.readline().split("\n")[0]
        configFile.close()
        charsAvalible = getCharsAvalible()
        for (name, i) in charsAvalible:
            if name == prevChar:
                return prevChar
    except IOError:
        prevChar = None
        
    return None

def showMainMenu():
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()
    
    # Background snow
    snow = []
    for apa in range (0,4000):
        snow.append(Snow(random.randint(0,640), random.randint(0,480), apa%2 + 1))
    
    
    prevChar = readPrevChar()
    
    files = os.listdir(os.getcwd())
    chars = getCharsAvalible()
    
    nextY = 112
    yGap = 0
    
    concaveImage = helperfunctions.renderTextBlock("Concave", g.fontBigger, 1, (255,255,255))
    concaveImagePos = (320 - concaveImage.get_width()/2, 32)
    resumeButton = helperfunctions.renderTextBlock("Resume game", g.fontBig, 1, (255,255,255))
    resumeButton = helperfunctions.addBorderCentered(resumeButton, 12)
    resumeButtonPos = (320 - resumeButton.get_width()/2, nextY)
    yGap += resumeButton.get_height()
    nextY += yGap
    
    
    selectChar = helperfunctions.renderTextBlock("Select character", g.fontBig, 1, (255,255,255))
    selectChar = helperfunctions.addBorderCentered(selectChar, 12)
    selectCharPos = (320 - selectChar.get_width()/2, nextY)
    nextY += yGap
    
    newChar = helperfunctions.renderTextBlock("Start new character", g.fontBig, 1, (255,255,255))
    newChar = helperfunctions.addBorderCentered(newChar, 12)
    newCharPos = (320 - newChar.get_width()/2, nextY)
    nextY += yGap
    
    showOptions = helperfunctions.renderTextBlock("Options", g.fontBig, 1, (255,255,255))
    showOptions = helperfunctions.addBorderCentered(showOptions, 12)
    showOptionsPos = (320 - showOptions.get_width()/2, nextY)
    nextY += yGap
    
    showCredits = helperfunctions.renderTextBlock("Show credits", g.fontBig, 1, (255,255,255))
    showCredits = helperfunctions.addBorderCentered(showCredits, 12)
    showCreditsPos = (320 - showCredits.get_width()/2, nextY)
    nextY += yGap
    
    exitGame = helperfunctions.renderTextBlock("Exit", g.fontBig, 1, (255,255,255))
    exitGame = helperfunctions.addBorderCentered(exitGame, 12)
    exitGamePos = (320 - exitGame.get_width()/2, nextY)
    nextY += yGap
    
    helpButton = helperfunctions.renderTextBlock("How to play", g.fontBig, 1, (255,255,255))
    helpButton = helperfunctions.addBorderCentered(helpButton, 12)
    helpButtonPos = (320 - helpButton.get_width()/2, nextY)
    
    backButton = helperfunctions.renderTextBlock("Back", g.fontBig, 1, (255,255,255))
    backButton = helperfunctions.addBorderCentered(backButton, 12)
    backButtonPos = (320 - exitGame.get_width()/2, 480 - backButton.get_height())
    
    
    typeText = helperfunctions.renderTextBlock("Type the name", g.fontBig, 1, (255,255,255))
    typeTextPos = (320 - exitGame.get_width()/2, 112)
    
    nameText = helperfunctions.renderTextBlock("Name: ", g.fontBig, 1, (255,255,255))
    nameTextPos = (320 - exitGame.get_width()/2, 178)
    
    
    
    
    helpA = "Move your char by using w, a, s & d.\n"
    helpA += "To pick up items/talk to npcs press e.\n"
    helpA += "Open inventory by pressing i or c."
    helpA += "To attack press left mousebutton,\n"
    helpA += "the direction of attack depends on where you click in the world.\n"
    helpA += "To use magic press a number (currently only 1-4).\n"
    
    helpText = helperfunctions.renderTextBlock(helpA, g.fontNormal, 1, (255,255,255))
    helpText = helperfunctions.addBorder(helpText)
    helpTextPos = (320 - helpText.get_width()/2, 112)
    
    showSelectChar = False
    showCreate = False
    showHelp = False
    
    name = ""
    validName = False
    while (True):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif (showCreate and event.type == KEYDOWN):
                if (event.key == K_a):
                    name += "a"
                elif (event.key == K_b):
                    name += "b"
                elif (event.key == K_c):
                    name += "c"
                elif (event.key == K_d):
                    name += "d"
                elif (event.key == K_e):
                    name += "e"
                elif (event.key == K_f):
                    name += "f"
                elif (event.key == K_g):
                    name += "g"
                elif (event.key == K_h):
                    name += "h"
                elif (event.key == K_i):
                    name += "i"
                elif (event.key == K_j):
                    name += "j"
                elif (event.key == K_k):
                    name += "k"
                elif (event.key == K_l):
                    name += "l"
                elif (event.key == K_m):
                    name += "m"
                elif (event.key == K_n):
                    name += "n"
                elif (event.key == K_o):
                    name += "o"
                elif (event.key == K_p):
                    name += "p"
                elif (event.key == K_q):
                    name += "q"
                elif (event.key == K_r):
                    name += "r"
                elif (event.key == K_s):
                    name += "s"
                elif (event.key == K_t):
                    name += "t"
                elif (event.key == K_u):
                    name += "u"
                elif (event.key == K_v):
                    name += "v"
                elif (event.key == K_w):
                    name += "w"
                elif (event.key == K_x):
                    name += "x"
                elif (event.key == K_y):
                    name += "y"
                elif (event.key == K_z):
                    name += "z"
                elif (event.key == K_BACKSPACE and len(name) > 0):
                    name = name[0:(len(name)-1)]
                
                if len(name) > 20:
                    name = name[0:20]
                
                
                if len(name) > 0:
                    validName = True
                    if len(name) > 1:
                        name = name[0].upper() + name[1:]
                    else:
                        name = name.upper()
                    
                    
                nameText = helperfunctions.renderTextBlock("Name: " + name, g.fontBig, 1, (255,255,255))
                
                for c in chars:
                    if c[0] == name:
                        validName = False
                
                if event.key == K_RETURN and validName:
                    showCreate = False
                    configFile = open("concave.cfg", "w")
                    configFile.write(name)
                    configFile.flush()
                    configFile.close()
                    pyhunter.concave(name)
                    prevChar = readPrevChar()
                    
                    chars = getCharsAvalible()
                    nameText = helperfunctions.renderTextBlock("Name: ", g.fontBig, 1, (255,255,255))
                
            elif (event.type == MOUSEBUTTONDOWN and event.button == 1): #Left button press
                (x, y) = event.pos
                
                
                if not showSelectChar and not showCreate and not showHelp:
                    if x >= resumeButtonPos[0] and x <= resumeButtonPos[0] + resumeButton.get_width():
                        if y >= resumeButtonPos[1] and y <= resumeButtonPos[1] + 7*resumeButton.get_height():
                            buttonId = (y - resumeButtonPos[1])/resumeButton.get_height()
                            if buttonId == 5:
                                sys.exit()
                            elif buttonId == 0 and prevChar:
                                # Free some mem
                                snow = []
                                
                                # Start game
                                pyhunter.concave(prevChar)
                                
                                # Recreate the "snow"
                                for apa in range (0,4000):
                                    snow.append(Snow(random.randint(0,640), random.randint(0,480), apa%2 + 1))
                            elif buttonId == 1 and len(chars) > 0:
                                showSelectChar = True
                                # List all .sav files
                            elif buttonId == 2 and len(chars) <= 5:
                                showCreate = True
                                name = ""
                            elif buttonId == 3:
                                pass # "options"
                            elif buttonId == 4:
                                ccredits.showCredits()
                            elif buttonId == 6:
                                showHelp = True
                elif showSelectChar:
                    if x >= backButtonPos[0] and x <= backButtonPos[0] + backButton.get_width() and y >= backButtonPos[1] and y <= 480:
                        showSelectChar = False
                    else:
                        for i in range(0,len(chars)):
                            if x >= 224 and x <= 224 + chars[i][1].get_width():
                                if y >= 112+i*chars[i][1].get_height() and y <= 112+(i+1)*chars[i][1].get_height():
                                    showSelectChar = False
                                    configFile = open("concave.cfg", "w")
                                    configFile.write(chars[i][0])
                                    configFile.flush()
                                    configFile.close()
                                    pyhunter.concave(chars[i][0])
                                    prevChar = readPrevChar()
                elif showCreate:
                    if x >= backButtonPos[0] and x <= backButtonPos[0] + backButton.get_width() and y >= backButtonPos[1] and y <= 480:
                        showCreate = False
                        name = ""
                        nameText = helperfunctions.renderTextBlock("Name: ", g.fontBig, 1, (255,255,255))
                    if validName and x >= backButtonPos[0] and x <= backButtonPos[0] + backButton.get_width() and y >= backButtonPos[1]-backButton.get_height() and y <= 480 - backButton.get_height():
                        showCreate = False
                        configFile = open("concave.cfg", "w")
                        configFile.write(name)
                        configFile.flush()
                        configFile.close()
                        pyhunter.concave(name)
                        prevChar = readPrevChar()
                        
                        chars = getCharsAvalible()
                        nameText = helperfunctions.renderTextBlock("Name: ", g.fontBig, 1, (255,255,255))
                elif showHelp:
                    if x >= backButtonPos[0] and x <= backButtonPos[0] + backButton.get_width() and y >= backButtonPos[1] and y <= 480:
                        showHelp = False
                                
                
        for apa in snow:
            apa.update()
        
        screen.fill((0x32, 0x21, 0x25))
                
        for apa in snow:
            screen.set_at(apa.getPos(), apa.color)
        
        screen.blit(concaveImage, concaveImagePos)
        
        if not showSelectChar and not showCreate and not showHelp:
            if prevChar:
                screen.blit(resumeButton, resumeButtonPos)
            if len(chars) > 0:
                screen.blit(selectChar, selectCharPos)
            if len(chars) <= 5:
                screen.blit(newChar, newCharPos)
            #screen.blit(showOptions, showOptionsPos)
            screen.blit(showCredits, showCreditsPos)
            screen.blit(exitGame, exitGamePos)
            screen.blit(helpButton, helpButtonPos)
        elif showSelectChar:
            for i in range(0,len(chars)):
                screen.blit(chars[i][1], (224, 112+i*chars[i][1].get_height()))
                
            screen.blit(backButton, backButtonPos)
        elif showCreate:
            screen.blit(typeText, typeTextPos)
            screen.blit(nameText, nameTextPos)
            if validName:
                screen.blit(newChar, (backButtonPos[0], backButtonPos[1] - backButton.get_height()))
            screen.blit(backButton, backButtonPos)
        elif showHelp:
            screen.blit(helpText, helpTextPos)
            screen.blit(backButton, backButtonPos)
        pygame.display.flip()
        
        
        clock.tick(60)
#showMainMenu()